/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 * BaseFlowRoleUserService
 * 流程角色人员
 * 修改纪录
 * 2021-01-11 版本：1.0 wanghanwei 创建。
 * 
 * @version 版本：1.0
 * @author 作者：wanghanwei
 * 创建日期：2021-01-11
 */
package com.topscomm.base.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.topscomm.base.BaseSystemConst.BaseFlowRoleUserTypeEnum;
import com.topscomm.base.pojo.BaseFlowRoleUserEntity;
import com.topscomm.base.service.IBaseFlowRoleUserService;
import com.topscomm.base.service.impl.auto.BaseFlowRoleUserServiceAuto;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboDeptEntity;
import com.topscomm.cbo.service.impl.CboDeptService;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.DatacodeCache;

@Service(value = "baseFlowRoleUserService")
@Scope(value = "singleton")
public class BaseFlowRoleUserService extends BaseFlowRoleUserServiceAuto implements IBaseFlowRoleUserService {
	@Autowired
	private CboDeptService cboDeptService;

	/**
	 * @description:批量保存
	 * @auther: wanghanwei
	 * @date: 2021年1月12日下午2:42:33
	 * @modify:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public ResponseResult<Object> saveBatch(Map<String, Object> paraMap) {
		String rolecode = ConvertUtil.convertToString(paraMap.get("rolecode"));
		String usertype = ConvertUtil.convertToString(paraMap.get("usertype"));
		String uscopetype = ConvertUtil.convertToString(paraMap.get("uscopetype"));
		String scopedeptList = ConvertUtil.convertToString(paraMap.get("scopedeptList"));
		Long roleid = ConvertUtil.convertToLong(paraMap.get("roleid"));
		List<Map<String, Object>> cboUserList = (List<Map<String, Object>>) paraMap.get("userList");
		if (StringUtils.isEmpty(rolecode)) {
			return ResponseResult.ok("角色编码为空！");
		}
		// 查询新增人员是否已存在
		List<BaseFlowRoleUserEntity> userInsList = this
				.queryByWhere("roleid='" + roleid + "' and userid in(" + paraMap.get("selectuserids") + ")");
		if (userInsList.size() > 0) {
			return ResponseResult.error("人员已存在！");
		}
		// 对接人只能有一个
		if (BaseFlowRoleUserTypeEnum.LinkMan.equals(usertype)) {
			String selectUserIdString = ConvertUtil.convertToString(paraMap.get("selectuserids"));
			if (selectUserIdString.indexOf(",") > -1) {
				return ResponseResult.error("同角色同范围下，只能有一个对接人！");
			}
			StringBufferProxy countWhere = new StringBufferProxy();
			countWhere.appendLineSingle("roleid='{0}'", roleid);
			countWhere.appendLineSingle(" and usertype='{0}'", BaseFlowRoleUserTypeEnum.LinkMan);
			countWhere.appendLineSingle(" and userid !={0}", selectUserIdString);
			if (!"0".equals(uscopetype)) {
				String[] deptList = scopedeptList.split(",");
				countWhere.appendLineSingle(" and scopetype ='{0}' and ( 1=2", uscopetype);
				for (String dept : deptList) {
					countWhere.appendLineSingle(" or {0} like '%,{1},%'", SQLAdapter.concat(new String[] { "','", "scopedept", "','" }), dept);
				}
				countWhere.appendLineSingle(")");
			} else {
				countWhere.appendLineSingle(" and scopetype ='{0}'", uscopetype);
			}
			int count = getCount(countWhere.toString());
			if (count > 0) {
				return ResponseResult.error("同角色同范围下，只能有一个对接人！");
			}
		}
		List<BasicEntity> baseFlowRoleUserEntityList = new ArrayList<BasicEntity>();
		for (Map<String, Object> map : cboUserList) {
			CboDeptEntity cboDeptEntity = cboDeptService.queryById(String.valueOf(map.get("deptid")));
			BaseFlowRoleUserEntity baseFlowRoleUserEntity = new BaseFlowRoleUserEntity();
			long[] arrayId = PrimaryKeyUtil.GeneIDs(baseFlowRoleUserEntity.getTableName(), cboUserList.size());
			baseFlowRoleUserEntity.setId(arrayId[0]);
			baseFlowRoleUserEntity.setRolecode(rolecode);
			baseFlowRoleUserEntity.setRoleid(roleid);
			baseFlowRoleUserEntity.setUsertype(usertype);
			baseFlowRoleUserEntity.setUserid(Long.valueOf(ConvertUtil.convertToString(map.get("id"))));
			baseFlowRoleUserEntity.setUsercode(ConvertUtil.convertToString(map.get("code")));
			baseFlowRoleUserEntity.setUsername(ConvertUtil.convertToString(map.get("name")));
			baseFlowRoleUserEntity.setDeptcode(cboDeptEntity.getCode());
			baseFlowRoleUserEntity.setDeptname(ConvertUtil.convertToString(map.get("dispdeptid")));
			baseFlowRoleUserEntity.setScopetype(uscopetype);
			if (!"0".equals(uscopetype)) {
				baseFlowRoleUserEntity.setScopedept(scopedeptList);
			}
			baseFlowRoleUserEntityList.add(baseFlowRoleUserEntity);
		}
		this.insertBatch(baseFlowRoleUserEntityList);
		return ResponseResult.ok("操作成功！");
	}

	/**
	 * @description:更新操作
	 * @auther: wanghanwei
	 * @date: 2021年1月29日下午8:48:25
	 * @modify:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public ResponseResult<Object> scopedeptUpdate(Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		Map<String, Object> updateData = (Map<String, Object>) paraMap.get("updateData");
		String selectuserids = ConvertUtil.convertToString(updateData.get("selectuserids"));
		if (StringUtils.isEmpty(selectuserids)) {
			// 对接人只能有一个
			String usertype = ConvertUtil.convertToString(paraMap.get("usertype"));
			if (BaseFlowRoleUserTypeEnum.LinkMan.equals(usertype)) {
				String uscopetype = ConvertUtil.convertToString(paraMap.get("uscopetype"));
				String scopedeptList = ConvertUtil.convertToString(paraMap.get("scopedeptList"));
				StringBufferProxy countWhere = new StringBufferProxy();
				countWhere.appendLineSingle("roleid='{0}'", paraMap.get("roleid"));
				countWhere.appendLineSingle(" and usertype='{0}'", BaseFlowRoleUserTypeEnum.LinkMan);
				countWhere.appendLineSingle(" and userid !={0}", paraMap.get("userid"));
				if (!"0".equals(uscopetype)) {
					String[] deptList = scopedeptList.split(",");
					countWhere.appendLineSingle(" and scopetype ='{0}' and ( 1=2", uscopetype);
					for (String dept : deptList) {
						countWhere.appendLineSingle(" or {0} like '%,{1},%'", SQLAdapter.concat(new String[] { "','", "scopedept", "','" }), dept);
					}
					countWhere.appendLineSingle(")");
				} else {
					countWhere.appendLineSingle(" and scopetype ='{0}'", uscopetype);
				}
				int count = getCount(countWhere.toString());
				if (count > 0) {
					return ResponseResult.error("同角色同范围下，只能有一个对接人！");
				}
			}
			// 更新范围省份
			if ("0".equals(paraMap.get("scopetype"))) {
				paraMap.put("scopedept", null);
			} else {
				paraMap.put("scopedept", ConvertUtil.convertToString(updateData.get("scopedeptList")));
			}
			this.update(paraMap);
			return ResponseResult.ok("操作成功！");
		} else {
			// 更新人员
			this.deleteByWhere("roleid='" + paraMap.get("roleid") + "' and userid in(" + paraMap.get("userid") + ")");
			return saveBatch(updateData);
		}
	}

	/**
	 * @author: wanghanwei
	 * @date: 2021-01-15
	 * @param mapRow
	 * @description:设置字段显示值
	 * @modify:
	 */
	@Override
	public void setDispFields(Map<String, Object> mapRow, DatacodeCache datacodeCache) {
		String temp;
		if (mapRow.get("scopetype") != null) {
			temp = mapRow.get("scopetype").toString();
			mapRow.put("dispscopetype", datacodeCache.getValueDynamic("FlowScopeType", temp, "code", "name"));
		}
		if (mapRow.get("enabled") != null) {
			temp = mapRow.get("enabled").toString();
			mapRow.put("dispenabled", datacodeCache.getValueDynamic("CboYesNo", temp, "code", "name"));
		}
		if (mapRow.get("usertype") != null) {
			temp = mapRow.get("usertype").toString();
			mapRow.put("dispusertype", datacodeCache.getValueDynamic("FlowRoleUserType", temp, "code", "name"));
		}
		if (mapRow.get("scopedept") != null) {
			// 将省区编码显示成省区名称
			String scopedeptString = StringUtils.strip(mapRow.get("scopedept").toString().replace("\"", ""), "[]");
			List<String> scopedeptList = Arrays.asList(scopedeptString.split(","));
			List<String> deptNameList = new ArrayList();
			// StringBuffer scopedepts = new StringBuffer();
			if (scopedeptList != null && !scopedeptList.isEmpty()) {
				for (String scopedept : scopedeptList) {
					deptNameList.add(ConvertUtil.convertToString(datacodeCache.getValueDynamic("CpDeptCommonCode", scopedept, "code", "name")));
				}
			}
			mapRow.put("dispscopedepts", String.join(",", deptNameList));
		}
	}
}
